from django.shortcuts import render
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import viewsets, filters
from rest_framework.pagination import PageNumberPagination
from users.models import Department, Employee
from users.serializers import DepartmentSerializer, EmployeeSerializer


# 标准化分页类，继承自DRF 的 PageNumberPagination
class StandardResultsSetPagination(PageNumberPagination):
    page_size = 10  # 默认页面显示10条数据
    page_query_description = 'page_size' # 查询的参数，允许用户自定义的
    max_page_size = 50 # 每页最大显示数量的限制，防止性能问题

# 部门模型的视图, 提供了完整的CRUD
class DepartmentViewSet(viewsets.ModelViewSet):
    queryset = Department.objects.all()  # 查询所有部门信息
    serializer_class = DepartmentSerializer # 使用序列化类
    pagination_class = StandardResultsSetPagination  # 使用标准分页类
    # 可以用于模糊查询和排序
    filter_backends = (filters.SearchFilter, filters.OrderingFilter)
    # 指定魔化查询的字典
    search_fields = ('title',)
    # 默认排序规则
    ordering = ('id',)  # 根据id升序排序

# 员工模型的视图，提供了完整的CURD
class EmployeeViewSet(viewsets.ModelViewSet):
    queryset = Employee.objects.all()
    serializer_class = EmployeeSerializer
    pagination_class = StandardResultsSetPagination
    filter_backends = (DjangoFilterBackend ,filters.SearchFilter,)
    search_fields = ('name',) # 根据名字模糊查询
    # 根据部门查询
    filter_fields = ('depart',)



